package com.ucode.wap.cgms.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.model.pay.notify.dto.PayOrderNotifyReqDTO;
import com.ucode.model.pay.notify.dto.PayRefundNotifyReqDTO;
import com.ucode.model.pay.order.PayOrder;
import com.ucode.model.pay.order.PayRefund;
import com.ucode.model.pay.order.enums.PayOrderStatusEnum;
import com.ucode.model.pay.order.enums.PayRefundStatusEnum;
import com.ucode.pay.service.PayOrderService;
import com.ucode.pay.service.PayRefundService;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.JsonUtils;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import com.ucode.wap.cgms.service.ApiCgmsCompanionOrderService;
import com.ucode.wap.cgms.service.ApiCgmsGiftRewardOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Tag(name = "移动端 - 陪玩社区系统 - 支付业务回调")
@RestController
@RequestMapping("/cgms/pay-notify")
@Validated
public class ApiCgmsPayNotifyController {

    private static Log log = LogFactory.get();
    @Resource
    private ApiCgmsCompanionOrderService apiCgmsCompanionOrderService;
    @Resource
    private ApiCgmsGiftRewardOrderService apiCgmsGiftRewardOrderService;
    //@Resource
    //private ApiEcmsAfterSaleOrderService apiEcmsAfterSaleOrderService;
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private PayRefundService payRefundService;

    @PostMapping(value = "/companion-order/pay-notify")
    @Operation(summary = "陪玩订单支付回调") //注意:由支付服务在支付成功后，会进行通知回调到该接口，不需要登录，需要做好安全校验
    public ResponseResult payNotify(@RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        log.info("陪玩订单支付回调结果:{}", JsonUtils.toJsonString(notifyReqDTO));

        //校验支付订单的合法性
        PayOrder payOrder = validatePayOrderNotify(notifyReqDTO);

        apiCgmsCompanionOrderService.paySuccess(Long.valueOf(payOrder.getMerchantOrderNo()),payOrder.getId(),payOrder.getPayType(),payOrder.getSuccessTime(),payOrder.getAmount());

        return ResponseResult.success();
    }

    @PostMapping(value = "/companion-order/refund-notify")
    @Operation(summary = "陪玩订单退款回调")
    public ResponseResult refundNotify(@RequestBody PayRefundNotifyReqDTO notifyReqDTO) {
        log.info("陪玩订单退款回调结果:{}", JsonUtils.toJsonString(notifyReqDTO));

        //校验退款订单的合法性
        PayRefund payRefund = payRefundService.validate(notifyReqDTO.getPayRefundId());
        // 校验退款单已退款完成
        if (!PayRefundStatusEnum.isSuccess(payRefund.getStatus())) {
            log.error("退款订单【编码：{}】 未退款成功，不能进行通知回调，请忽非法请求！",payRefund.getId());
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        //校验业务订单号
        if(!ObjUtil.equals(payRefund.getMerchantRefundId(),notifyReqDTO.getMerchantOrderId())) {
            log.error("退款订单【编码：{}】 商户业务订单编号错误，不能进行通知回调，请忽非法请求！",payRefund.getId());
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        //apiEcmsAfterSaleOrderService.refundSuccess(Long.valueOf(payRefund.getMerchantRefundId()),payRefund.getId(),payRefund.getSuccessTime(),payRefund.getRefundAmount());
        return ResponseResult.success();
    }



    @PostMapping(value = "/reward-order/pay-notify")
    @Operation(summary = "打赏订单支付回调") //注意:由支付服务在支付成功后，会进行通知回调到该接口，不需要登录，需要做好安全校验
    public ResponseResult payNotifyByRewardOrder(@RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        log.info("打赏订单支付回调:{}", JsonUtils.toJsonString(notifyReqDTO));

        //校验支付订单的合法性
        PayOrder payOrder = validatePayOrderNotify(notifyReqDTO);
        apiCgmsGiftRewardOrderService.paySuccess(Long.valueOf(payOrder.getMerchantOrderNo()),payOrder.getId(),payOrder.getPayType(),payOrder.getSuccessTime(),payOrder.getAmount());
        return ResponseResult.success();
    }


    /**
     * 验证支付回调结果
     * @param notifyReqDTO
     * @return
     */
    private PayOrder validatePayOrderNotify(PayOrderNotifyReqDTO notifyReqDTO){
        //校验支付订单的合法性
        PayOrder payOrder = payOrderService.validate(notifyReqDTO.getPayOrderId());
        // 校验支付单已支付
        if (!PayOrderStatusEnum.isSuccess(payOrder.getStatus())) {
            log.error("支付订单【编码：{}】 未支付，不能进行通知回调，请忽非法请求！",payOrder.getId());
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        //校验业务订单号
        if(!ObjUtil.equals(payOrder.getMerchantOrderNo(),notifyReqDTO.getMerchantOrderId())) {
            log.error("支付订单【编码：{}】 商户业务订单编号错误，不能进行通知回调，请忽非法请求！",payOrder.getId());
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        return payOrder;
    }

}
